package com.example.controller;

import com.example.pojo.User;
import com.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.ui.Model;

import java.util.Objects;

@Controller
public class UserController {

    @Autowired
    @Qualifier("userServiceImpl")
    private UserService userService;

    //9999源unl localhost:8080/hello?a=1&b=2
    //Restful风格 localhost:8080/hello/1/2    @RequestMapping("hello/{a}/{b}“)   @PathVariable int a
    @RequestMapping("/hello")
    public String test(@RequestParam("name") String name,@RequestParam("password")  String password, Model module){
        module.addAttribute("msg","name :"+ name + password);
        //web-inf/jsp/hello
        return "hello";//被解析
    }
    @PostMapping("/login")//登录
    public String login(@RequestParam("id") String id,
                        @RequestParam("password") String password,
                        Model model)
    {
        if (userService.login(id,password) != null){
            User user = userService.login(id,password);
            model.addAttribute("id",user.getId());
            model.addAttribute("name",user.getName());
            model.addAttribute("user_information",user.getUser_information());
            return "user";
        }
        else {
            model.addAttribute("msg","登录失败");
            return "failed";
        }

    }
    @PostMapping("/addUser")//注册
    public String addUser(@RequestParam("id") String id,@RequestParam("name") String name,
                          @RequestParam("password") String password ,
                          Model model)
    {
         String msg = userService.addUser(id, name, password);
        if(Objects.equals(msg, "注册成功")){
             model.addAttribute("msg",msg);
             return "success";
         }else {
            model.addAttribute("msg",msg);
            return "failed";
        }
    }

    @GetMapping("/addUser") //跳转到注册页面
    public String addUser(){
        return "addUser";
    }
    @GetMapping("/login") //跳转到登录页面
    public String login(){
        return "login";
    }

    @PostMapping("/updatePassword") //修改用户密码
    public String changepassword(@RequestParam("userId") String id,
                                 @RequestParam("newPassword") String password,
                                 Model model)
    {
        String msg = userService.changePassword(id,password);
        model.addAttribute("msg",msg);
        return "success";
    }
    @PostMapping("/deleteUser") //注销用户
    public String changepassword(@RequestParam("userId") String id,Model model){
        String msg = userService.deleteUser(id);
        model.addAttribute("msg",msg);
        return "success";
    }
}
